package com.suixun.dao.redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;  
import org.springframework.data.redis.connection.RedisConnection;  
import org.springframework.data.redis.core.RedisCallback;  
import org.springframework.stereotype.Repository;
import com.suixun.dao.redis.base.AbstractBaseRedisDao;
  
@SuppressWarnings("static-access")
@Repository("redisDao")
public class RedisDao<T> extends AbstractBaseRedisDao<String, T> {  
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    public T get(Object key) {
        final String keyf = (String) key;
        Object object = null;
        try {

            object = redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {

                    byte[] key = keyf.getBytes();
                    byte[] value = connection.get(key);
                    if (value == null) {
                        return null;
                    }
                    return toObject(value);

                }
            });
            return (T)object;
        } catch (Exception e) {
            return null;
        }
    }

    public void put(Object key, T value) {
        final String keyf = (String) key;
        final Object valuef = value;
        try {
            redisTemplate.execute(new RedisCallback<Long>() {
                @Override
                public Long doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] keyb = keyf.getBytes();
                    byte[] valueb = toByteArray(valuef);
                    connection.set(keyb, valueb);
                    connection.expire(keyb, 86400);
                    return 1L;
                }
            });
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}  